package edu.cth.speedapp;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;

public abstract class NFCActivity extends Activity {

    
    private NfcAdapter mAdapter;
	private PendingIntent pendingIntent;
	private boolean nfcActive;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAdapter = NfcAdapter.getDefaultAdapter(this);
       if(mAdapter == null){
    	   
    	 //  Toast.makeText(this, "NFC not found!", Toast.LENGTH_LONG).show();
       }else{
    	   pendingIntent = PendingIntent.getActivity(
    			   this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
       }
       
       
    }
    @Override
    protected void onStart() {
    	super.onStart();
    	Intent intent = this.getIntent();
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if(tag != null){
 	   		tagRead(tag);
 	   	}
    }
    

    public final boolean isNFCPossibleOnDevice(){
    	return mAdapter != null;
    	
    }
    
    protected void onResume() {
        super.onResume();

        if(mAdapter != null){
        	mAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
        }
    }
    @Override
    protected void onPause() {
    	super.onPause();
    	if(mAdapter != null){
    		mAdapter.disableForegroundDispatch(this);
    	}
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
    	Log.d("lol", "mytag: newintent");
    	super.onNewIntent(intent);
    	Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    	if(tag != null && nfcActive){
    		tagRead(tag);
    	}
    }

    public abstract void tagRead(Tag tag);
    

    public static String bytesToHex(byte[] bytes) {
        final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        char[] hexChars = new char[bytes.length * 2];
        int v;
        for ( int j = 0; j < bytes.length; j++ ) {
            v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
    

    
    
}
